import sys
from math import sqrt
num_items = 6095
def build_item_cat(item_file):
    cat_index = {}
    tot = 0
    for line in open(item_file):
        iid, cat, desc = line.split()
        iid = int(iid)
        cat = cat.split('.')
        l = []
        for i in range(1, len(cat)+1):
            c = '.'.join(cat[0:i])
            if not c in cat_index:
                cat_index[c] = tot
                tot += 1
            l.append( cat_index[c] )
        cat_index[iid] = l
    return cat_index

if __name__ == '__main__':
    if len(sys.argv) != 5:
        print 'usage: <item.ridx> <itemf> <depth-list> <offset>'
        sys.exit(1)
        
    dlist = map(int, sys.argv[3].split(","))
    offset = int(sys.argv[4])
    
    cat_index = build_item_cat(sys.argv[1])

    ofile = open(sys.argv[2], "w")
    for i in range(num_items):
        l = []
        for k, c in enumerate(cat_index[i]):
            if k+1 in dlist:
                l.append( c )
        v = 1./sqrt(len(l)) if len(l) else 0
        desc = " ".join(map(lambda x: "%d:%.3f" % (x+offset, v), l))
        ofile.write("%d %s\n" % (len(l), desc))
    ofile.close()
    
